using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;

using Framework;

namespace SchemaMonitor
{
    [Serializable()]
    public partial class CNodeList : List<CNode>
    {
        #region Constructors
        //Basic constructor
        public CNodeList() : base() {}
       
        //More efficient memory-allocation if size is known
        public CNodeList(int capacity) : base(capacity) {}
        
        //Shares the index (if its already been computed)
        public CNodeList(CNodeList list) : base(list.Count)
        {
            foreach (CNode i in list)
                base.Add(i);
        }

        //Generic list (eg. from paging control), have to assume type
        public CNodeList(IList list) : base(list.Count)
        {
            foreach (CNode i in list)
                base.Add(i);
        }
        #endregion
        
        #region Top/Bottom/Page
        public CNodeList Top(int count)
        {
            if (count >= this.Count)
                return this;
            return Page(count, 0); 
        }
        public CNodeList Bottom(int count)   
        {
            if (count > this.Count)
                count = this.Count;
            return new CNodeList(this.GetRange(this.Count - count - 1, count));
        }
        public CNodeList Page(int pageSize, int pageIndex)
        {
            return new CNodeList( CUtilities.Page(this, pageSize, pageIndex) );
        }
        #endregion

        #region BulkEditLogic
        public bool HaveSameValue(string propertyName)               { return CReflection.HaveSameValue(this, propertyName); }
        public void SetSameValue( string propertyName, object value) {        CReflection.SetSameValue( this, propertyName, value); }
        #endregion

        #region SortBy
        //Public
        public CNodeList SortBy(string propertyName) { return SortBy(propertyName, false); }
        public CNodeList SortBy(string propertyName, bool descending)
        {
            CNodeList copy = new CNodeList(this);
            if (this.Count == 0)    return copy;
            copy.Sort(new CNodeList_SortBy(propertyName, descending, this));
            return copy;
        }
        //Private 
        private class CNodeList_SortBy : CReflection.GenericSortBy, IComparer<CNode>
        {
            public CNodeList_SortBy(string propertyName, bool descending, IList list) : base(propertyName, descending, list) { }
            public int Compare(CNode x, CNode y) { return base.Compare(x, y); }
        }
        #endregion

        #region SaveAll/DeleteAll
        //Use default connection (may be overridden in base class)
        public void SaveAll()   {   if (this.Count > 0) { SaveAll(  this[0].DataSrc);    }    }
        public void DeleteAll() {   if (this.Count > 0) { DeleteAll(this[0].DataSrc);    }    }

        //Use connection supplied
        public void SaveAll(  CDataSrc dataSrc) {   dataSrc.BulkSave(this);    }
        public void DeleteAll(CDataSrc dataSrc) {   dataSrc.BulkDelete(this);  }

        //Use transaction supplied
        public void SaveAll(  IDbTransaction txOrNull)    {   foreach (CNode i in this) {   i.Save(  txOrNull);   }   }
        public void DeleteAll(IDbTransaction txOrNull)    {   foreach (CNode i in this) {   i.Delete(txOrNull);   }   }

        //Use a specified isolation level
        public void SaveAll(  IsolationLevel txIsolationLevel)   {   if (this.Count > 0) { SaveAll(  this[0].DataSrc, txIsolationLevel);  }    }
        public void DeleteAll(IsolationLevel txIsolationLevel)   {   if (this.Count > 0) { DeleteAll(this[0].DataSrc, txIsolationLevel);  }    }

        //Use a specified connection and isolation level
        public void SaveAll(  CDataSrc dataSrc, IsolationLevel txIsolationLevel)   {   dataSrc.BulkSave(  this, txIsolationLevel);  }
        public void DeleteAll(CDataSrc dataSrc, IsolationLevel txIsolationLevel)   {   dataSrc.BulkDelete(this, txIsolationLevel);  }
        #endregion

        #region List of Ids
        List<Guid> _ids;
        public List<Guid> Ids
        {
            get
            {
                if (null == _ids)
                {
                    List<Guid> ids = new List<Guid>(this.Count);
                    foreach (CNode i in this)
                        ids.Add(i.NodeGuid);
                    _ids = ids;
                }
                return _ids;
            }
        }
        public CNodeList GetByIds(List<Guid> ids)
        {
            CNodeList list = new CNodeList(ids.Count);
            foreach (Guid id in ids)
                if (null != GetById(id))
                    list.Add(GetById(id));
            return list;
        }
        #endregion
        
        #region Cache-Control
        //Main Logic
    
        //Supplementary List Overloads
        public void Add(   IList<CNode> itemsToAdd)    {   foreach (CNode i in itemsToAdd)   { Add(   i); }   }
        public void Remove(IList<CNode> itemsToRemove) {   foreach (CNode i in itemsToRemove){ Remove(i); }   }
		#endregion

		#region Main Index (on NodeGuid)
		public bool Has(Guid nodeGuid)
		{
			return null != GetById(nodeGuid);
		}
		public CNode GetById(Guid nodeGuid)
        {
            CNode c = null;
            Index.TryGetValue(nodeGuid, out c);
            return c;
        }
        [NonSerialized]
        private Dictionary<Guid,CNode> _index;
        private Dictionary<Guid,CNode> Index
        {
            get
            {
                if (null != _index)
                    if (_index.Count == this.Count)
                        return _index;

                    _index = new Dictionary<Guid,CNode>(this.Count);
                        foreach (CNode i in this) 
                            _index[i.NodeGuid] = i;
                return _index;
            }
        }
		#endregion

		#region Foreign-Key Indices (Subsets)
		//Index by NodeTypeId
		public CNodeList GetByTypeId(string sig)
		{
			var s = CSignature.Cache.GetByHash(new CSignature(sig).SigHash)[0];
			return GetByTypeId(s.SigTypeId);
		}
		public CNodeList GetByTypeId(int typeId)
		{
			CNodeList temp = null;
			if (!IndexByTypeId.TryGetValue(typeId, out temp))
			{
				temp = new CNodeList();
				IndexByTypeId[typeId] = temp;
			}
			return temp;
		}
		[NonSerialized]
		private Dictionary<int, CNodeList> _indexByTypeId;
		public Dictionary<int, CNodeList> IndexByTypeId
		{
			get
			{
				if (null == _indexByTypeId)
				{
					Dictionary<int, CNodeList> index = new Dictionary<int, CNodeList>();
					CNodeList temp = null;
					foreach (CNode i in this)
					{
						if (!index.TryGetValue(i.NodeTypeId, out temp))
						{
							temp = new CNodeList();
							index[i.NodeTypeId] = temp;
						}
						temp.Add(i);
					}
					_indexByTypeId = index;
				}
				return _indexByTypeId;
			}
		}

		//Index by NodeUserId
		public CNodeList GetByUserId(long userId)
        {
            CNodeList temp = null;
            if (! IndexByUserId.TryGetValue(userId, out temp))
            {
                temp = new CNodeList();
                IndexByUserId[userId] = temp;
            }
            return temp;
        }

        [NonSerialized]
        private Dictionary<long, CNodeList> _indexByUserId;
        private Dictionary<long, CNodeList> IndexByUserId
        {
            get
            {
                if (null == _indexByUserId)
                {
                    Dictionary<long, CNodeList> index = new Dictionary<long, CNodeList>();
                    CNodeList temp = null;
                    foreach (CNode i in this)
                    {
                        if (! index.TryGetValue(i.NodeUserId, out temp))
                        {
                            temp = new CNodeList();
                            index[i.NodeUserId] = temp;
                        }
                        temp.Add(i);
                    }
                    _indexByUserId = index;
                }
                return _indexByUserId;
            }
        }
        //Index by NodeDataIsGz
        public CNodeList GetByDataIsGz(bool dataIsGz)
        {
            CNodeList temp = null;
            if (! IndexByDataIsGz.TryGetValue(dataIsGz, out temp))
            {
                temp = new CNodeList();
                IndexByDataIsGz[dataIsGz] = temp;
            }
            return temp;
        }

        [NonSerialized]
        private Dictionary<bool, CNodeList> _indexByDataIsGz;
        private Dictionary<bool, CNodeList> IndexByDataIsGz
        {
            get
            {
                if (null == _indexByDataIsGz)
                {
                    Dictionary<bool, CNodeList> index = new Dictionary<bool, CNodeList>();
                    CNodeList temp = null;
                    foreach (CNode i in this)
                    {
                        if (! index.TryGetValue(i.NodeDataIsGz, out temp))
                        {
                            temp = new CNodeList();
                            index[i.NodeDataIsGz] = temp;
                        }
                        temp.Add(i);
                    }
                    _indexByDataIsGz = index;
                }
                return _indexByDataIsGz;
            }
        }
        #endregion

    }
}
